//
//  SNTopRankingViewController.swift
//  eyepetizer
//
//  Created by stone on 16/6/2.
//  Copyright © 2016年 stone. All rights reserved.
//

import UIKit

class BEMyOrdersListController: UIViewController {
    
    var orderChooseToolBar: KKOrderChooseToolBar = KKOrderChooseToolBar()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !BEAccountModel.isLogin(){
            let alertVC = UIAlertController(title: "Please login first!", message: "Log in before you can view the orders", preferredStyle: .alert)
            
            let cancleAction = UIAlertAction(title: "Later", style: .cancel) { (_) in
                if self.view.subviews.count == 0{
                    return
                }
                self.collectionView.removeFromSuperview()
                self.orderChooseToolBar.removeFromSuperview()
            }

            let doneAction = UIAlertAction(title: "Login Now", style: .default) { (_) in
                    _ = isLogin()
            }
            alertVC.addAction(cancleAction)
            alertVC.addAction(doneAction)
            
            UIApplication.shared.keyWindow?.rootViewController!.present(alertVC, animated: true, completion: nil)
            return
        }
        //        navigationItem.rightBarButtonItem = UIBarButtonItem.rightItem("Create", target: self, action: #selector(rightBtnClick))
        setupUI()
    }
    
    private func setupUI(){
        view.backgroundColor = UIColor.white
        view.addSubview(orderChooseToolBar)
        view.addSubview(collectionView)
        
//        orderChooseToolBar.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: 40)
//        collectionView.frame = CGRect(x: 0, y: 104, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 148)
        orderChooseToolBar.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(orderChooseToolBar.snp.bottom)
            make.height.equalTo(SCREEN_HEIGHT - 148)
        }
        
        orderChooseToolBar.selectedIndexCallBack = { (index: Int) -> () in
            // 滚动collectionView
            let indexPath = IndexPath(item: index, section: 0)
            self.collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
            weak var weakSelf = self
            DispatchQueue.main.async(execute: {
                weakSelf?.collectionView.reloadData()
            })
        }
        
    }
    
    @objc private func rightBtnClick (){
        let newOrderVC = UIStoryboard(name: "BENewOrderController", bundle: nil).instantiateInitialViewController()!
        navigationController?.pushViewController(newOrderVC, animated: true)
    }
    
    // 显示表情视图
    lazy var collectionView: UICollectionView = {
        // 流水布局
        let layout = UICollectionViewFlowLayout()
        // 设置布局方向
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 148)
        let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        cv.dataSource = self
        // 设置代理
        cv.delegate = self
        // 注册cell
        cv.register(BEMyOrdersCollectionCell.self, forCellWithReuseIdentifier: "BEMyOrdersCollectionCell")
        
        // 设置分页滚动
        cv.isPagingEnabled = true
        //
        cv.bounces = false
        cv.backgroundColor = UIColor(white: 0.95, alpha: 1)
        return cv
    }()
}

extension BEMyOrdersListController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 两个item
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BEMyOrdersCollectionCell", for: indexPath) as! BEMyOrdersCollectionCell
        
        //此处针对Save状态的订单,push到创建订单页面
        cell.pushCreateOrderBlock = {() -> () in
            let newOrderVC = UIStoryboard(name: "BENewOrderController", bundle: nil).instantiateInitialViewController()!
            self.navigationController?.pushViewController(newOrderVC, animated: true)
        }
        
        cell.pushOrderDetailVcBlock = {(orderId: Int64,techDataCount: Int,ispayFooter: Int) -> () in
            let orderDetailVC = BEOrderDetailController()
            orderDetailVC.orderId = orderId
            orderDetailVC.techDataCount = techDataCount
            orderDetailVC.ispayfooter = ispayFooter
            self.navigationController?.pushViewController(orderDetailVC, animated: true)
        }
        cell.backgroundColor = UIColor.white
        cell.index = indexPath.item
        return cell
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取collectionView的 '中心点' 所在的的位置
        var center =  collectionView.center
        center.x = center.x + collectionView.contentOffset.x
        //判断当前屏幕显示的两个cell的frame 谁包含了这个中心点
        let indexPaths = collectionView.indexPathsForVisibleItems
        for indexPath in indexPaths {
            let cell = collectionView.cellForItem(at: indexPath)
            //判断frame是否包含了 '中心点'
            if cell!.frame.contains(center) {
                //可以设置toolbar选中的按钮
                orderChooseToolBar.setSelectedBtn(section: indexPath.item)
            }
        }
    }
}
